package hu.bme.mit.rifl.business.base;

import hu.bme.mit.rifl.datamodel.Order;

import com.ibm.mq.MQC;
import com.ibm.mq.MQException;
import com.ibm.mq.MQGetMessageOptions;
import com.ibm.mq.MQMessage;
import com.ibm.mq.MQPutMessageOptions;
import com.ibm.mq.MQQueue;
import com.ibm.mq.MQQueueManager;

/**
 * Wrapper facade for establishing the connection to the MQ manager and for
 * sending and receiving work items.
 */
public class RiflOrderQueue {

	private MQQueue queue;
	private MQQueueManager manager;

	public RiflOrderQueue(String queueName) {
		try {
			manager = new MQQueueManager("QM_winxp_vm");

			int openOprionsArg = MQC.MQOO_INPUT_AS_Q_DEF | MQC.MQOO_OUTPUT;

			queue = manager.accessQueue(queueName, openOprionsArg);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Puts a single order into the respective queue.
	 * 
	 * @param order
	 *            workitem of type hu.bme.mit.rifl.datamodel.Order
	 */
	public void put(Order order) {
		MQMessage m = new MQMessage();
		MQPutMessageOptions mo = new MQPutMessageOptions();

		try {
			m.writeObject(order);
			queue.put(m, mo);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Gets a single order from the respective queue.
	 * 
	 * @return workitem of type hu.bme.mit.rifl.datamodel.Order
	 */
	public Order get() {
		MQMessage m = new MQMessage();
		MQGetMessageOptions gmo = new MQGetMessageOptions();
		try {
			queue.get(m, gmo);
			return (Order) m.readObject();
		} catch (Exception e) {
		}
		return null;
	}

	/**
	 * Closes the connection to the manager.
	 */
	public void close() {
		try {
			queue.close();
			manager.disconnect();
		} catch (MQException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
